package com.xiran.controller;

import com.xiran.service.UserService;
import com.xiran.util.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * 认证控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/auth")
public class AuthController {

    @Autowired
    private UserService userService;
    
    @Autowired
    private JwtUtils jwtUtils;
    
    /**
     * 用户登录，生成JWT令牌
     */
    @PostMapping("/login")
    public Map<String, Object> login(@RequestBody Map<String, String> loginInfo) {
        String username = loginInfo.get("username");
        String password = loginInfo.get("password");
        
        // 1. 验证用户名和密码（实际项目中应调用UserService进行验证）
        boolean isAuthenticated = userService.verifyPassword(username, password);
        
        if (!isAuthenticated) {
            return createResponse(false, "用户名或密码错误", null);
        }
        
        // 2. 生成JWT令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put("username", username);
        // 可以添加其他自定义信息，如角色、权限等
        claims.put("role", "USER");
        
        String token = jwtUtils.generateToken(claims);
        
        // 3. 返回结果
        Map<String, String> data = new HashMap<>();
        data.put("token", token);
        
        return createResponse(true, "登录成功", data);
    }
    
    /**
     * 创建统一响应格式
     */
    private Map<String, Object> createResponse(boolean success, String message, Object data) {
        Map<String, Object> response = new HashMap<>();
        response.put("success", success);
        response.put("message", message);
        response.put("data", data);
        return response;
    }
}
